package cn.edu.ctbu.datajpacrud.service;



import cn.edu.ctbu.datajpacrud.domain.Teacher;
import cn.edu.ctbu.datajpacrud.exception.REnum;
import cn.edu.ctbu.datajpacrud.exception.RException;
import cn.edu.ctbu.datajpacrud.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TeacherService {
 @Autowired
 private TeacherRepository teacherRepository;


 public Teacher findByNameAndPassword(String name,String password) throws Exception{

  List<Teacher> byNameAndPassword = teacherRepository.findByNameAndPassword(name,password);
  if(byNameAndPassword.size()>0){
   return byNameAndPassword.get(0);
  }else{
   throw new RException(REnum.LOGIN_ERR);
  }
 }

 public List<Teacher> findAll(){

  return teacherRepository.findAll();
 }

 /**
  *按id进行查询
  * @param id 主键，整数
  * @return
  */
 public Teacher findById(Integer id){


  return  teacherRepository.findById(id).orElse(null);
 }

 /**
  *按名字进行查询，like
  * @param name 主键，整数
  * @return
  */
 public List<Teacher> findByName(String name){


  return  teacherRepository.findByNameLike(name);
 }



 public Teacher insert(Teacher teacher){
  teacherRepository.save(teacher);
  return teacher;
 }

 public Teacher update(Teacher teacher){

  teacherRepository.save(teacher);
  return teacher;
 }
 /**public void delete(Integer id){

  teacherRepository.deleteById(id);
  }**/
 public void delete(Teacher teacher){
  teacherRepository.delete(teacher);
 }

 public void delete(Integer id){

  Teacher teacher=new Teacher();
  teacher.setId(id);
  teacherRepository.delete(teacher);

 }

 public Teacher getById(Integer id){

  Teacher teacher=teacherRepository.findById(id).orElse(null);
  return teacher;
 }
}

